<script lang="ts" setup>
import "@/utils/rem"
import { reactive, ref } from "vue"
import { useRouter } from "vue-router"
import { useCascaderAreaData } from "@vant/area-data"
import { showToast } from "vant"
import { getProductInfoApi } from "@/api/yunShang"
import { createH5OrderDataApi } from "@/api/orderH5Ys"
document.title = ""
// import { formatDateTime } from "@/utils"
const router = useRouter()
const pid = router.currentRoute.value.query.pid
const sid = router.currentRoute.value.query.sid
const tid = router.currentRoute.value.query.tid

const showBottom = ref<boolean>(false)
const carderAd = ref<string>("")
const cascaderValue = ref<string>("")

const show = ref<boolean>(false)

const formData = reactive<any>({
  data: {}
})
const imgTopUrl = ref<string>("")
const imgDetailUrl = ref<string>("")
const productName = ref<string>("")
const options = useCascaderAreaData()
const onFinish = ({ selectedOptions }: any) => {
  show.value = false
  carderAd.value = selectedOptions.map((option: any) => option.text).join("/")
}
/**获取产品详情 */
const getProduct = async () => {
  await getProductInfoApi({ id: pid }).then((res: any) => {
    console.log(res)
    if (res.code == 200) {
      imgTopUrl.value = `http://fansitexitong.cn/image/${res.data.img}`
      imgDetailUrl.value = `http://fansitexitong.cn/image/${res.data.back}`
      // imgTopUrl.value = `http://192.168.0.152:8080/image/${res.data.img}`
      // imgDetailUrl.value = `http://192.168.0.152:8080/image/${res.data.back}`
      productName.value = res.data.name
      document.title = res.data.name
    }
  })
}
getProduct()
const onSubmit = async (values: any) => {
  console.log(values)
  const PReg =
    /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/
  if (!formData.data.takeMobile || !PReg.test(formData.data.takeMobile)) {
    showToast(`请输入正确的手机号`)
    return
  }
  if (!carderAd.value || !formData.data.h5_address) {
    showToast(`请输入收货地址`)

    return
  }
  console.log(carderAd.value)

  //身份证姓名汉字验证
  const NameReg = /^(?:[\u4e00-\u9fa5·]{2,16})$/
  if (!formData.data.cardName || !NameReg.test(formData.data.cardName)) {
    showToast(`请输入正确的姓名`)
    return
  }

  const arrExp = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2] //加权因子
  const arrValid = [1, 0, "X", 9, 8, 7, 6, 5, 4, 3, 2] //校验码
  if (/^\d{17}\d|x$/i.test(formData.data.cardID)) {
    let sum = 0
    const idx = ref<any>()
    for (let i = 0; i < formData.data.cardID.length - 1; i++) {
      // 对前17位数字与权值乘积求和
      sum += parseInt(formData.data.cardID.substr(i, 1), 10) * arrExp[i]
    }
    // 计算模（固定算法）
    idx.value = sum % 11
    // 检验第18为是否与校验码相等
    if (arrValid[idx.value] == formData.data.cardID.substr(17, 1).toUpperCase()) {
      console.log(1)
    } else {
      showToast("身份证号不正确！")
      return
    }
  } else {
    showToast("身份证号不正确！")
    return
  }
  /**下单逻辑 */
  formData.data.takeAddress = `${carderAd.value.replace(/\//g, " ")} ${formData.data.h5_address}`
  formData.data.sku = pid
  formData.data.systemId = sid
  formData.data.recorder = tid
  formData.data.consignee = formData.data.cardName
  await createH5OrderDataApi(formData.data)
    .then((res: any) => {
      if (res.code == 200) {
        // 清空reactive对象里面的key值
        formData.data = {}
        carderAd.value = ""
        cascaderValue.value = ""
        showToast("下单成功")
        showBottom.value = false
        // formData.data.takeAddress = ""
      }
    })

    .finally(() => {
      carderAd.value = ""
      cascaderValue.value = ""
    })
}
</script>
<template>
  <div style="max-width: 750px; margin: 0 auto" class="bg">
    <van-image width="100%" height="5.8rem" :src="imgTopUrl" />
    <div class="view1">
      <h2>{{ productName }}</h2>
      <div class="view_7">商品详情</div>
      <van-image width="100%" height="auto" :src="imgDetailUrl" />
    </div>
    <div class="view_bottom">
      <van-button round icon="guide-o" type="primary" @click="showBottom = true">免费领取</van-button>
    </div>
    <van-button type="success" round class="orderSearch" size="mini" to="/orderSearch"> 订单查询 </van-button>
    <van-popup
      v-model:show="showBottom"
      closeable
      round
      close-icon="close"
      :close-on-click-overlay="false"
      position="bottom"
      :style="{ height: '60%' }"
    >
      <div class="pop">
        <h1 class="title">填写信息</h1>
        <h2 class="view_7">收货信息</h2>
        <van-form @submit="onSubmit">
          <van-cell-group inset>
            <van-field
              v-model="formData.data.cardName"
              name="姓名"
              label="姓名"
              size="small"
              placeholder="请输入身份证姓名(已加密)"
            />
            <van-field
              v-model="formData.data.cardID"
              name="身份证号"
              label="身份证号"
              size="small"
              placeholder="请输入身份证号(已加密)"
            />
            <van-field
              v-model="formData.data.takeMobile"
              name="手机号"
              label="手机号"
              size="small"
              placeholder="请输入手机号(已加密)"
            />
            <van-field
              v-model="carderAd"
              is-link
              size="small"
              readonly
              label="收货地址"
              placeholder="请选择所在地区"
              @click="show = true"
            />
            <van-popup v-model:show="show" round position="bottom">
              <van-cascader
                v-model="cascaderValue"
                title="请选择所在地区"
                :options="options"
                @close="show = false"
                @finish="onFinish"
              />
            </van-popup>
            <van-field
              v-model="formData.data.h5_address"
              name="详细地址"
              label="详细地址"
              size="small"
              placeholder="如街道,道路,小区,门牌号"
            />
          </van-cell-group>
          <div style="margin: 16px">
            <van-button round block type="primary" native-type="submit"> 立即领取 </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>
  </div>
</template>
<style lang="scss" scoped>
.bg {
  height: 100%;
  // background: url("@/assets/layout/ordersearch.png") no-repeat;
  background-size: 100% 100%;
  background-color: #fff;
  overflow-y: auto;
}
:deep(.van-image) {
  display: block !important;
}
.view1 {
  width: 94%;
  margin: 0 auto;
  padding-bottom: 1.1rem;
}
h2 {
  font-size: 14px;
  font-weight: bold;
  padding: 8px 0;
}
.view_7 {
  font-weight: bold;
  font-size: 16px;
  position: relative;
  padding-left: 15px;
  margin: 25px 0;
}
.view_7::after {
  position: absolute;
  content: "";
  left: 0;
  top: 0;
  width: 3px;
  height: 16px;
  background: #1a54fa;
  border-radius: 2px;
}
.view_bottom {
  position: fixed;
  bottom: 0;
  background: #fff;
  padding: 9px 3%;
  width: 94%;
  box-shadow: 0px 2px 8px #ccc;
  max-width: calc(640px - 6%);
  box-sizing: initial;
  line-height: 0;
  :deep(.van-button) {
    width: 100%;
  }
}

.orderSearch {
  position: fixed;
  padding: 0.22rem;
  // padding-right: 0.2rem;
  top: 1rem;
  right: -0.2rem;
  background-color: rgba(0, 0, 0, 0.3);
  color: #fff;
  border: 0;
  font-size: 14px;
  font-weight: 700;
}
.pop {
  padding: 0.2rem;
  .view_7::after {
    top: 8px;
  }
}
.title {
  font-size: 18px;
  font-weight: 700;
  text-align: center;
}
</style>
